package com.example.yml0612;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;

import com.example.sql.MyOpenHelper;
import com.example.yuanmenglong0612.R;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public class Main2Activity extends AppCompatActivity {
    List<Bean.DataBean.PhonesBean> phones;
    StringBuffer append;
    String url;
    ListView listView;
    private MyOpenHelper openHelper;
    LvAdapter lvAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        in();
        listView = findViewById(R.id.lv);
        openHelper = new MyOpenHelper(this);
        lvAdapter = new LvAdapter(phones, this);
        listView.setAdapter(lvAdapter);

    }

    public void in() {
        AssetManager assets = getAssets();
        try {
            StringBuffer stringBuffer = new StringBuffer();
            InputStream open = assets.open("phonedata.json");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(open));
            String inen;
            while ((inen = bufferedReader.readLine()) != null) {
                append = stringBuffer.append(inen);
            }
            url = append.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        Bean bean = gson.fromJson(url, Bean.class);
        phones = bean.getData().getPhones();
        SQLiteDatabase db = openHelper.getWritableDatabase();
        ContentValues values = null;
        for (int i = 0; i < phones.size(); i++) {

            Bean.DataBean.PhonesBean phonesBean = phones.get(i);
            phonesBean.setImage(R.mipmap.b);
            values = new ContentValues();
            values.put("name", phonesBean.getName());
            values.put("brand", phonesBean.getBrand());
            values.put("price", phonesBean.getPrice());
            db.insert("phone", null, values);
        }
        db.close();
    }
}

